import 'package:flutter/material.dart';
import 'package:znmm/network/notify_listener.dart';
import '../mag/news_mag.dart';
import '../model/news_model.dart';
import 'news_cell.dart';

class NewsList extends StatefulWidget {
  const NewsList({
    super.key,
  });

  @override
  State<NewsList> createState() => _NewsListState();
}

class _NewsListState extends State<NewsList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  List<NewsModel> _newList = [];
  int _iNotiId1 = -1;
  int _iNumber = 0;

  bool _bIsAnimated = false; //添加快讯是否需要动画

  @override
  void initState() {
    super.initState();

    _newList = NewsMag().getNewList();
    NewsMag().reqFlashNews(
      callback: (p0) {
        if (mounted) {
          print("----------刷新快讯----------");
          setState(() {
            if (_listKey.currentState != null) {
              _bIsAnimated = false;
              for (int iIndex = 0; iIndex < p0; iIndex++) {
                _listKey.currentState!.insertItem(0);
              }
            }
          });
        }
      },
    );

    //---添加监听者
    _iNotiId1 = NotifyCenter().addObserver(NotifyKey.newAddMsgKey, (object) {
      addMessage();
    });
  }

  @override
  void dispose() {
    NotifyCenter().removeCallback(_iNotiId1);

    super.dispose();
  }

  void addMessage() {
    _bIsAnimated = true;
    _newList.insert(
        0,
        NewsModel(
          title: 'Dart 2.15 发布$_iNumber',
          occurrenceTime: 'Dart 2.15 版本发布$_iNumber',
        ));
    _listKey.currentState
        ?.insertItem(0, duration: const Duration(milliseconds: 500));

    _iNumber++;
  }

  @override
  Widget build(context) {
    //配合shrinkWrap: true使用，解决数据少的时候数据底部对齐的问题
    return Align(
      alignment: Alignment.topCenter,
      child: AnimatedList(
        key: _listKey,
        initialItemCount: _newList.length,
        itemBuilder: (context, index, animation) {
          //print("AnimatedList:$index");
          NewsModel pmodel = _newList[index];

          return _bIsAnimated
              ? SlideTransition(
                  position: Tween<Offset>(
                    begin: const Offset(1, 0), // 从右侧进入
                    end: const Offset(0, 0),
                  ).animate(animation),
                  child: NewsCell(pmodel: pmodel),
                )
              : NewsCell(pmodel: pmodel);
        },
      ),
    );
  }
}
